package xin.jiangqiang;

import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsRequest;
import com.aliyuncs.alidns.model.v20150109.DescribeDomainRecordsResponse;
import xin.jiangqiang.entity.Aliyun;
import xin.jiangqiang.util.AliDdnsUtils;
import xin.jiangqiang.util.LocalPublicIpv4;
import xin.jiangqiang.util.PropertiesUtil;

import java.util.List;

/**
 * @author JiangQiang
 * @date 2019/4/7 15:40
 */
public class UpdateDomainRecord {
    /**
     * 设置域名参数
     *
     * @param request
     */
    public void setParam(DescribeDomainRecordsRequest request) {
        String domainName = PropertiesUtil.getProperty("DomainName");
        request.putQueryParameter("DomainName", domainName);
    }

    /**
     * 解析DNS信息
     */
    public void analysisDns() {
        // 获取公网ip
        LocalPublicIpv4 ip = new LocalPublicIpv4();
        String ipV4 = ip.publicip();
        // 获取解析的数据
        String actionName = "DescribeDomainRecords";
        DescribeDomainRecordsResponse response;
        // 获取request
        DescribeDomainRecordsRequest request = AliDdnsUtils.getRequestQuery(actionName);
        // 设置request参数
        setParam(request);
        try {
            response = AliDdnsUtils.getClient().getAcsResponse(request);
            // 声明解析对象
            DemoListDomains demo = new DemoListDomains();
            // 获取阿里云的数据
            List<DescribeDomainRecordsResponse.Record> list = response.getDomainRecords();
            if (list == null || list.isEmpty()) {
                return;
            }
            //更新ip
            DescribeDomainRecordsResponse.Record record = null;
            for (DescribeDomainRecordsResponse.Record rec : list) {
                String rr = PropertiesUtil.getProperty("RR");
                if (rec.getRR().equals(rr)) {
                    record = rec;
                }
            }
            Aliyun yun = new Aliyun();
            // 进行判定记录是否需要更新
            if (record.getValue().equals(ipV4)) {
                // 不需要更新，继续下次循环
                System.out.println("当前域名解析地址为：" + ipV4 + "不需要更新！");
            } else {
                System.out.println("当前域名解析地址为：" + ipV4);
                System.out.println("更新域名：" + record.getRR() + "." + record.getDomainName());
                // 进行替换关键数据
                yun.setIpV4(ipV4);
                yun.setRecordId(record.getRecordId());
                yun.setRr(record.getRR());
                yun.setTTL(record.getTTL());
                yun.setType(record.getType());
                System.out.println("域名更换ip开始");
                demo.analysisDns(yun);
                System.out.println("域名更换ip结束");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("域名更换异常");
        }
    }
}
